from flask import Blueprint, render_template, request, jsonify, current_app, redirect, url_for, g

from application import db
from common.libs.UserSerivice import UserService
from web.models.user import User

route_user = Blueprint('user_page', __name__)


@route_user.route("/login", methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template("user/login.html")
    elif request.method == 'POST':
        resp = {"code": 200, "msg": "登录成功", "data": {}}
        req = request.values
        login_name = req["login_name"] if "login_name" in req else ""
        login_pwd = req["login_pwd"] if "login_pwd" in req else ""
        if (not login_name) or len(login_name) < 1:
            resp["code"] = -1
            resp["msg"] = "请输入正确的登录用户名"
            return jsonify(resp)
        if (not login_pwd) or len(login_pwd) < 1:
            resp["code"] = -1
            resp["msg"] = "请输入正确的密码"
            return jsonify(resp)

        user_info = User.query.filter_by(login_name=login_name).first()
        if not user_info:  # 数据库查不到用户名
            resp["code"] = -1
            resp["msg"] = "请输入正确的用户名"
            return jsonify(resp)
        # 当存在用户名，则查密码
        # 用户的加密的盐值，可以理解为加密种子，不同的用户加密盐是不同的，当创建用户时，会自动生成该用户的加密盐值
        salt = user_info.login_salt
        # 取得通过明文密码加密后生成的密文   明文密码： 123456  --改用户的加密盐：cF3JfH5FJfQ8B2Ba
        gen_pwd = UserService.genPwd(login_pwd, salt)  # 跟注册时相同的加密机制
        if user_info.login_pwd != gen_pwd:
            resp["code"] = -1
            resp["msg"] = "请输入正确的密码"
            return jsonify(resp)
        # 登录成功
        # resp = {"code": 200, "msg": "登录成功", "data": {}}
        resp['data']['username'] = login_name
        resp['data']['password'] = login_pwd
        response = jsonify(resp)
        # auth_code:
        print("auth_code", UserService.genAuthCode(user_info))
        # cookie_str=bdc556da52d17c3f664aa50c1d1c77cc#1
        cookie_str = UserService.genAuthCode(user_info) + "#" + str(user_info.uid)
        # 用cookie实现登录态的保持
        response.set_cookie(current_app.config.get("AUTH_COOKIE_NAME"), cookie_str, max_age=7 * 24 * 60 * 60)
        return response


@route_user.route("/logout")
def logout():
    response = redirect(url_for('user_page.login'))
    response.delete_cookie(current_app.config['AUTH_COOKIE_NAME'])
    return response


@route_user.route("/edit", methods=["GET", "POST"])
def edit():
    if request.method == "GET":
        return render_template("user/edit.html")
    resp = {"code": 200, "msg": "操作成功", "data": {}}
    req = request.values
    nickname = req["nickname"] if "nickname" in req else ""
    email = req["email"] if "email" in req else ""
    if (not nickname) or len(nickname) < 1:
        resp["code"] = -1
        resp["msg"] = "请输入符合规范的姓名"
        return jsonify(resp)
    if (not email) or len(email) < 1:
        resp["code"] = -1
        resp["msg"] = "请输入符合规范的邮箱"
        return jsonify(resp)
    # 修改当前登录人姓名和邮箱
    user_info = g.current_user
    user_info.nickname = nickname
    user_info.email = email
    # 提交到数据库
    db.session.add(user_info)
    db.session.commit()
    return jsonify(resp)


@route_user.route("/reset-pwd", methods=["GET", "POST"])
def resetPwd():
    if request.method == "GET":
        return render_template("user/reset_pwd.html")
    resp = {"code": 200, "msg": "修改密码成功", "data": {}}
    req = request.values
    old_password = req["old_password"] if "old_password" in req else ""
    new_password = req["new_password"] if "new_password" in req else ""
    if (not old_password) or len(old_password) < 1:
        resp["code"] = -1
        resp["msg"] = "请输入正确的原密码"
        return jsonify(resp)
    if (not new_password) or len(new_password) < 6:
        resp["code"] = -1
        resp["msg"] = "请输入不少于6位的新密码"
        return jsonify(resp)
    if old_password == new_password:
        resp["code"] = -1
        resp["msg"] = "新旧密码一致"
        return jsonify(resp)

    user_info = g.current_user
    salt = user_info.login_salt
    gen_pwd = UserService.genPwd(old_password, salt)  # 跟注册时相同的加密机制
    if user_info.login_pwd != gen_pwd:
        resp["code"] = -1
        resp["msg"] = "原密码不对~"
        return jsonify(resp)

    user_info.login_pwd = UserService.genPwd(new_password, salt)
    #提交到数据库
    db.session.add(user_info)
    db.session.commit()

    response = jsonify(resp)
    cookie_str = UserService.genAuthCode(user_info) + "#" + str(user_info.uid)
    response.set_cookie(current_app.config.get("AUTH_COOKIE_NAME"), cookie_str, max_age=7 * 24 * 60 * 60)
    return response
